<template>
  <cl-drawer ref="drawer" :props="{
    title: `${editing ? '编辑' : '新增'}预约`,
    size: '700px',
    appendToBody: true
  }" showConfirm confirmText="提交预约" @close="reset" @confirm="submit" :saving="saving">
    <el-form ref="form" label-position="top" :model="form" :rules="rules" :disabled="saving">
      <el-form-item label="预约信息">
        <el-card shadow="never">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预约客户" prop="cus_id">
                <cl-select-load-more ref="selectCus" v-model="form.cus_id" placeholder="手机号/微信号/客户名称/会员号"
                  style="width: 100%" :apiFn="apiCusFn" keyword="search_content" :clearable="false"
                  @change-list="changeCusList" @change="changeCus">
                  <template v-slot="{ data }">
                    <el-option v-for="item in data" :key="item.cus_id" :label="item.cus_name" :value="item.cus_id" />
                  </template>
                </cl-select-load-more>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预约时长" prop="cart_duration">
                <cart-duration v-model="form.cart_duration" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>
      <el-form-item label="预约服务" prop="serviceList">
        <cl-service-card :biz_id="form.biz_id" v-model="form.serviceList" />
      </el-form-item>
      <el-form-item label="预约备注" prop="remarks">
        <el-input v-model="form.remarks" placeholder="请填写预约备注" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <perfect-cus-info ref="perfectInfo" />
  </cl-drawer>
</template>
<script>
import PerfectCusInfo from "@/components/perfect-cus-info/index.vue";
import CartDuration from "@/components/cart-duration.vue";
export default {
  name: "appoint-form",
  components: {
    PerfectCusInfo,
    CartDuration
  },
  data() {
    return {
      form: {
        cart_id: undefined,
        bed: 1,
        biz_id: "", //事业部id
        dept_id: "", //门店id
        bra_id: "",
        add_dept_id: [], //预约部门
        add_user_id: "", //预约人
        // dept_ids: [],
        cus_id: "", //客户名
        cus_mobile: "", //客户手机
        appoint_time: "",
        appoint_date: "", //预约日期
        appoint_btime: "", //预约开始时间
        appoint_etime: undefined, //预约结束时间
        serviceList: [], //已选服务列表
        remarks: "", //备注信息
        source_add: 1,
        cart_duration: "" // 预约时长
        // region: "",
        // date1: "",
        // date2: "",
        // delivery: false,
        // type: [],
        // resource: "",
        // desc: ""
      },
      rules: {
        cus_id: [{ required: true, message: "请选择预约客户" }],
        cart_duration: [{ required: true, message: "请选择预约时长" }],
        serviceList: [
          {
            // type: "array",
            required: true,
            message: "请选择预约服务"
          }
        ]
      },
      cusList: [], //预约客户列表
      editing: false,
      saving: false
    };
  },
  computed: {
    bizRefData() {
      const { biz_id } = this.form;
      return this.getBizRefData(biz_id);
    }
  },
  methods: {
    async open(data = {}) {
      this.$refs.drawer.create(() => {
        Object.keys(this.form).forEach(key => {
          data[key] != undefined && (this.form[key] = data[key]);
        });
      });
      console.log('222', this.form);
    },
    setData(data = {}) {
      let test = [
        "dept_id",
        "appoint_time",
        "appoint_date",
        "appoint_btime"
      ];
      Object.keys(this.form).forEach(key => {
        if (test.indexOf(key) === -1 && data[key] != undefined) {
          this.form[key] = data[key];
        }
      });
      if (!data.serviceList && data.service_info) {
        this.form.serviceList = data.service_info.map(v => {
          return {
            ...v,
            si_id: v.id,
            si_name: v.name,
            price: v.unit_price
          };
        });
      }
      console.log('111', this.form);
    },
    // initBizRefData() {
    // 	const { biz_id } = this.form;
    // 	this.getBizRefBrand(biz_id);
    // 	this.getBizRefShop(biz_id);
    // },
    //获取默认服务
    async getDefaultser(cus_id) {
      const { biz_id } = this.form;
      let data = await this.$service.cart.getDefaultser({
        biz_id,
        cus_id
      });
      if (data.length) {
        this.form.serviceList.push({
          is_presents: 0,
          is_experience: 0,
          si_id: data[0].si_id,
          si_name: data[0].si_name,
          price: data[0].price
        });
      }
    },
    reset() {
      this.$resetFields(this.form);
      this.form.source_add = 1;
      this.form.cart_duration = "";
      this.$refs.form.resetFields();
    },
    close() {
      this.$refs.drawer.close();
    },
    submit() {
      this.$refs.form.validate(async (valid, errors) => {
        this.showFormErr(errors);
        if (!valid) return;

        const { serviceList, dept_ids, add_dept_id, ...args } = this.form;
        let items = serviceList.map(v => ({
          type: v.type || 1,
          id: v.si_id,
          prod_id: v.si_id,
          name: v.si_name,
          lasttime: v.lasttime,
          picture_url: v.picture_url,
          product_category: v.product_category,
          unit_price: v.price,
          price: v.price,
          maintain_type: v.maintain_type || 0,
          is_presents: v.is_presents,
          is_experience: v.is_experience
        }));
        let form = {
          ...args,
          add_dept_id: add_dept_id[2] || 0,
          items: JSON.stringify(items)
        };
        if (this.editing) {
          form.update_type = 4;
        }
        console.log(this.form, 'form');

        this.saving = true;
        await this.$service.cart[this.editing ? "updateCart" : "add"](form).done(() => {
        	this.saving = false;
        });
        this.$message.success("操作成功");
        this.$emit("confirm");
        this.close();
      });
    },
    // 获取客户列表
    async apiCusFn(v) {
      if (this.isSearchAstrict(v.search_content)) return {};
      const { biz_id, bed } = this.form;
      let query = {
        ...v,
        biz_id,
        dept_id: "",
        size: v.page_size
        // inherit: 0
      };
      const list = await this.$service.customer.searchCus(query);
      return {
        data: (list || []).map(v => ({
          ...v,
          dept_id: v.dept_id == 0 ? "" : v.dept_id
        })),
        total: list.length
      };
    },
    // 客户列表变化
    changeCusList(list) {
      this.cusList = list;
    },
    // 选择客户
    changeCus(cus_id) {
      console.log('chuafa1');

      let res = this.cusList.find(v => v.cus_id == cus_id);
      if (!res) return;
      // 是否重粉
      let isInherit = !!Number(res.inherit_id);
      if (isInherit) {
        this.confirm(`当前客户是重粉客户，是否继续预约？`)
          .then(() => {
            this.form.cus_mobile = res.cus_mobile;
            this.form.bra_id = res.bra_id;
          })
          .catch(() => {
            this.form.cus_id = "";
          });
        return;
      }

      if (!this.isPerfectInfo(res)) return;
      if (res.un_finish == 1 || res.un_finish == 2) {
        this.getCartList(cus_id, res.un_finish, res.biz_id);
        return;
      }

      if (res.cus_type == 2) {
        // this.form.serviceList = [];
        // this.getDefaultser(cus_id);
        this.confirm(`当前客户是老客只能进行维护，是否前往维护？`)
          .then(() => {
            this.close();
            this.$emit("to-maintain", res, this.form);
          })
          .finally(() => {
            this.form.cus_id = "";
          });

        return;
      }
      this.form.cus_mobile = res.cus_mobile;
      this.form.bra_id = res.bra_id;
    },
    // 判断是否完善手机个门店
    isPerfectInfo(cus) {
      const { cus_mobile, dept_id } = cus;
      if (!cus_mobile || !dept_id) {
        const promptStr =
          !cus_mobile && !dept_id
            ? "“所属门店”和“手机号”"
            : !cus_mobile
              ? "手机号"
              : "所属门店";
        this.confirm(`客户信息未完善，请完善客户的${promptStr}后再进行预约!`)
          .then(() => {
            // this.edit();
            this.$refs.selectCus.reset();
            this.$refs.perfectInfo.open(cus);
          })
          .catch(() => { })
          .finally(() => {
            this.form.cus_id = "";
          });

        return false;
      }
      return true;
    },
    // 获取预约订单列表
    async getCartList(cus_id, un_finish, biz_id) {
      const { list } = await this.$service.cart.page({
        cus_id,
        biz_id,
        search_content: cus_id,
        search_type: 7,
        status: 1
      });
      if (un_finish === 2 && list && list[0]) {
        this.editing = true;
        let obj = list[0]
        obj.bed = this.form.bed
        this.setData(obj);
        return;
      }
      if (list.length && list[0].status != 7 && list[0].status != 6) {
        this.confirm("当前已存在一笔预约，是否改约?")
          .then(() => {
            this.close();
            this.$emit("edit-appoint", {
              ...list[0],
              appoint_time: this.form.appoint_time,
              appoint_date: this.form.appoint_date,
              appoint_btime: this.form.appoint_btime
            });
          })
          .catch(() => { })
          .finally(() => {
            this.form.cus_id = "";
            this.form.cus_mobile = "";
            this.form.bra_id = "";
          });
        return;
      }

      console.log("获取预约订单列表", list);
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-col {
    min-height: 78px;
  }
}
</style>
